//
//  BCResourceDownloadHelper.m
//  断点上传和下载
//
//  Created by aaaa on 2020/5/7.
//  Copyright © 2020 aaaa. All rights reserved.
//

#import "BCResourceDownloadHelper.h"

#define DocumentPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]
#define CachePath [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]

#define DocumentFilePath(A) [DocumentPath stringByAppendingPathComponent:A]
#define CacheFilePath(A) [CachePath stringByAppendingPathComponent:A]


@implementation BCResourceDownloadHelper

+(NSString *)handleUrl:(NSString *)url{
    if (url == nil || ![url isKindOfClass:[NSString class]] || url.length == 0) {
        return @"";
    }
    NSCharacterSet *set = [NSCharacterSet URLFragmentAllowedCharacterSet];
    return [url stringByAddingPercentEncodingWithAllowedCharacters:set];
}

+(NSString *)getDownloadInfoCachePathWithUrl:(NSString *)url{
    if (![self urlIsValid:url]) {
        return @"";
    }
    NSString *cacheDir = [self createFilePath:CacheFilePath(@"BCDownloadInfo")];
    NSString *cachePath = [cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.plist", url.lastPathComponent]];
    NSLog(@"getDownloadInfoCachePathWithUrl = %@",cachePath);
    return cachePath;
}

+(NSString *)getSavePathWithUrl:(NSString *)url{
    if (![self urlIsValid:url]) {
        return @"";
    }
    NSString *saveDir = [self createFilePath:DocumentFilePath(@"BCFile")];
    NSString *savePath = [saveDir stringByAppendingPathComponent:url.lastPathComponent];
    NSLog(@"getSavePathWithUrl = %@",savePath);
    return savePath;
}

///创建文件
+ (NSString *)createFilePath:(NSString *)filePath {
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    if (!existed) {
        BOOL isSuccess = [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
        if (isSuccess) {
            return filePath;
        }
    } else {
        return filePath;
    }
    return @"";
}

+ (BOOL)urlIsValid:(NSString *)url{
    if (url == nil || ![url isKindOfClass:[NSString class]] || url.length == 0) {
        return NO;
    }
    return YES;
}
@end
